const Service = require('egg').Service;

const _ = require('lodash')

class AppService extends Service {

    /**
     * 保存批次
     * 
     * @param {any} para 参数信息
     * @returns 
     * @memberof AppService
     */
    async save(para) {
        const { app } = this
        const { Batch, BatchProduct } = app.model;
        const { customer_id, remark, products, sum, fee, total, confirm } = para

        let batch;
        //删除草稿批次
        let cgBatch = await Batch.find({
            where: {
                customer_id,
                status: 1
            }
        })
        if (cgBatch) {
            //删除批次产品
            await BatchProduct.destroy({
                where: {
                    batch_id: cgBatch.id
                }
            })
            cgBatch.destroy()
        }
        //插入草稿批次
        batch = await Batch.create({
            name: '草稿',
            status: 1,
            status_text: '草稿',
            customer_id,
            remark,
            sum, fee, total, confirm,
        })
        //插入批次产品
        for (let p of products) {
            p.id = null
            p.batch_id = batch.id
            p.customer_id = customer_id
            await BatchProduct.mySave(p)
        }

        return batch.get({ plain: true })
    }


    /**
     * 发布报价
     * 
     * @param {any} { batch_id, status, status_text } 
     * @memberof AppService
     */
    async publish({ id, status, status_text }) {
        const { app } = this
        const { Batch, BatchProduct } = app.model;
        let ret = await Batch.update({
            status,
            status_text
        }, {
                where: { id }
            })
        return ret
    }

    /**
     * 获取批次信息
     * 
     * @param {any} { batch_id } 
     * @memberof AppService
     */
    async getBatchAndProduct({ id }) {
        const { app: { model: { Batch, BatchProduct } } } = this
        const ret = await Batch.findOne({
            include: [BatchProduct],
            where: {
                id
            }
        })
        return ret
    }


    /**
     * 分页查询批次信息
     * 
     * @memberof AppService
     */
    async page(query) {
        const { app: { model: { Batch, Customer } } } = this

        const ret = await Batch.findAndCountAll({
            include: [{
                model: Customer,
                attributes: [['name', 'customer_name'], 'dept']
            }],
            raw: true,
            where: query.where
        })

        return ret
    }
}

module.exports = AppService